package bfs;

import java.util.*;

/**
 * @author wcj
 * @Date 2021/7/6 21:36
 * @Version 1.0
 */
public class MinBridge {

    private static int count;
    private static int[][] tmp;
    private static int row;
    private static int col;
    private static Queue<List<Integer>> queue;

    /**
     * 最短的桥：二维数组中存放二进制0和1，其中有两座岛屿（连续的1表示岛屿），求岛屿之间的最短的桥
     * 思路：
     * ①先通过深搜将一座桥全部变为2，并且记录其坐标
     * ②然后遍历整个数组，通过标记好的桥找另一座桥，看需要走几步
     *
     * @param arr
     * @return
     */
    public static int bfs(int[][] arr) {
        count = 0;
        tmp = arr;
        row = tmp.length;
        col = tmp[0].length;
        queue = new LinkedList<>();
        boolean flag = true;
        // 深搜，找到一座桥进行记录
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (tmp[i][j] == 1 && flag) {
                    dfs(i, j);
                    flag = false;
                }
            }
        }
        // 广搜,向上下左右四个方向进行搜索
        int[][] direction = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
        while (!queue.isEmpty()) {
            int len = queue.size();
            for (int i = 0; i < len; i++) {
                List<Integer> poll = queue.poll();
                int x = poll.get(0);
                int y = poll.get(1);
                for (int j = 0; j < direction.length; j++) {
                    int X = x + direction[j][0];
                    int Y = y + direction[j][1];
                    if (X < 0 || X >= row || Y < 0 || Y >= col) {
                        continue;
                    }
                    if (tmp[X][Y] == 0) {
                        tmp[X][Y] = 2;
                        queue.add(Arrays.asList(X, Y));
                    }
                    if (tmp[X][Y] == 1) {
                        return count;
                    }
                }
            }
            count++;
        }
        return count;
    }

    public static void dfs(int i, int j) {
        // 截止条件
        if (i < 0 || i >= row || j < 0 || j >= col) {
            return;
        }
        if (tmp[i][j] == 1) {
            tmp[i][j] = 2;
            queue.add(Arrays.asList(i, j));
            dfs(i - 1, j);
            dfs(i + 1, j);
            dfs(i, j - 1);
            dfs(i, j + 1);
        }
    }
}
